<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generator异步编程基本概念</title>
</head>
<body>
    <h1>Generator异步编程基本概念</h1>

    <script>
        // 同步执行的Generator函数
        function* synchronousGen() {
            const result = yield 1;
            return result;
        }

        // 异步执行的Generator函数
        function* asyncGen() {
            const result = yield new Promise(resolve => 
                setTimeout(() => resolve('完成'), 1000)
            );
            console.log(result);
        }

        // Generator函数的数据交换
        function* dataExchange() {
            const result1 = yield 'hello';
            console.log('第一次输入:', result1);
            const result2 = yield 'world';
            console.log('第二次输入:', result2);
        }

        const exchange = dataExchange();
        console.log('第一次输出:', exchange.next().value);
        console.log('第二次输出:', exchange.next('你好').value);
        exchange.next('世界');

        // 异步操作的同步表达
        function* loadUI() {
            showLoadingScreen();
            yield loadUIDataAsync();
            hideLoadingScreen();
        }

        // 模拟UI加载函数
        function showLoadingScreen() {
            console.log('显示加载画面');
        }

        function hideLoadingScreen() {
            console.log('隐藏加载画面');
        }

        function loadUIDataAsync() {
            return new Promise(resolve => {
                setTimeout(() => {
                    console.log('数据加载完成');
                    resolve('UI数据');
                }, 1000);
            });
        }

        // 执行UI加载
        const ui = loadUI();
        ui.next().value.then(() => ui.next());
    </script>
</body>
</html> 